using System;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class DoWhileStatementCodeGenerator
	{
		public static void GenerateBytecode(Context ctx, Statement stmt)
		{
			DoWhileStatement wstmt = (DoWhileStatement) stmt;
			LocalBuilder expr = ctx.il.DeclareLocal(typeof(Value));
			
			Label beginLabel = ctx.il.DefineLabel();
			Label conditionLabel = ctx.il.DefineLabel();
			Label endLabel = ctx.il.DefineLabel();
			
			ctx.il.MarkLabel(beginLabel);
			
			wstmt.stmt.GenerateBytecode(CodeUtilities.MakeWhileContext(ctx, wstmt.name, conditionLabel, endLabel));
			
			ctx.il.MarkLabel(conditionLabel);
			
			wstmt.e.GenerateBytecode(ctx, expr);
			ctx.il.Emit(OpCodes.Ldloc, expr);
			ctx.il.Emit(OpCodes.Callvirt, typeof(Value).GetMethod("ToBoolean"));
			ctx.il.Emit(OpCodes.Brfalse, endLabel);
			
			ctx.il.Emit(OpCodes.Br, beginLabel);
			ctx.il.MarkLabel(endLabel);
		}
	}
}

